#include <QUrl>
#include <QDebug>

#include "blogmanager.h"
#include "cvsession.h"
#include "util/cvutil.h"
#include "http/cvhttp.h"
#include "commentmanager.h"

BlogManager::BlogManager()
{
}

void BlogManager::getBlog(const QString &id)
{
    CVSession *session = CVSession::get();
    QString network = session->getCurrentNetwork()->getUrl();
    QUrl requestUrl = CVUtil::getBaseUrl("blogs.get_blog_by_id", network);
    requestUrl.addQueryItem("blog_id", id);
    CVHttp *http = new CVHttp(requestUrl);
    http->setDebug(true);
    connect(http, SIGNAL(finished(QScriptValue,QString)), this, SLOT(parseData(QScriptValue,QString)));
}

void BlogManager::getBlogComments(const QString &id, int limit, int offset)
{
    CommentManager *commentMgr = new CommentManager();
    commentMgr->getBlogComments(id, limit, offset);
    connect(commentMgr, SIGNAL(handleComments(QList<Comment*>*,QString)),
            this, SIGNAL(handleComments(QList<Comment*>*,QString)));
}

void BlogManager::parseData(QScriptValue json, const QString &msg)
{
    if (!json.isNull() && !json.isError())
    {
        json = json.property("0");
        Blog *blog = new Blog();
        blog->setId(json.property("id").toString());
        blog->setTitle(json.property("title").toString());
        blog->setDescription(json.property("desc").toString());
        blog->setTimeCreated(json.property("time_created").toString());
        blog->setOwner(json.property("owner").toString());
        blog->setOwnerIcon(json.property("owner_icon").toString());
        blog->setCommentCount(json.property("count_comments").toInt32());
        emit handleBlog(blog, "");
    }
    else
    {
        emit handleBlog(0, msg);
    }
}
